﻿using System;
using System.Diagnostics;
using System.ServiceProcess;

namespace TShooter.TfsSearch.Engine
{
    public partial class Service : ServiceBase
    {
        private ServerManagerCollection _Servers;
        private int _CurrentServer;

        public Service()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
#if DEBUG
            Debugger.Break();
#endif
            GetServers();
            StartEngines();
        }

        private void StartEngines()
        {
            _CurrentServer = -1;
            StartNextServer();
        }

        private void StartNextServer()
        {
            if (CurrentServer != null)
            {
                CurrentServer.Finished -= Server_Finished;
            }

            if ((++_CurrentServer) >= _Servers.Count)
            {
                _CurrentServer = -1;
                GoIdle();
                return;
            }

            CurrentServer.Finished += Server_Finished;
            CurrentServer.Start();
        }

        private void GoIdle()
        {
            // TODO: GoIdle
        }

        private void Server_Finished(object sender, EventArgs e)
        {
            StartNextServer();
        }

        private ServerManager CurrentServer
        {
            get
            {
                bool hasActiveServer = _CurrentServer >= 0 && _CurrentServer < _Servers.Count;
                return hasActiveServer ? _Servers[_CurrentServer] : null;
            }
        }

        private void GetServers()
        {
            _Servers = ServerManager.GetRegisteredServers();

            if (_Servers == null || _Servers.Count == 0)
            {
                Logger.Write(LogLevel.Error, LogCategory.General,
                             "There are no registered servers. Check service settings. Unable to proceed.");
                Stop();
            }
        }

        protected override void OnStop()
        {
        }
    }
}